package com.lgc.javathread.threadWaitTest.waitNotify.example1;

public class Program2 {
    public static void main(String[] args) {
        SyncStack ss = new SyncStack();
        MyProducer producer = new MyProducer(ss);
        MyConsumer consumer = new MyConsumer(ss);

        new Thread(producer).start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(consumer).start();
    }
}

class WoTou {
    int id;

    public WoTou(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "WoTou : " + id;
    }
}

class SyncStack {
    int index = 0;
    WoTou[] arrWT = new WoTou[6];

    public synchronized void push(WoTou wt) {
        if (index == arrWT.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.notify();
        arrWT[index] = wt;
        index++;
    }

    public synchronized WoTou pop() {
        if (index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.notify();
        index--;
        return arrWT[index];
    }
}

class MyProducer implements Runnable {
    SyncStack ss = null;
    public MyProducer(SyncStack ss) {
        this.ss = ss;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            WoTou wt = new WoTou(i);
            ss.push(wt);
            System.out.println("生产了一个：" + wt);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyConsumer implements Runnable {
    SyncStack ss = null;

    public MyConsumer(SyncStack ss) {
        this.ss = ss;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            WoTou wt = ss.pop();
            System.out.println("消费了一个：" + wt.toString());

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

